/**
 *    https://gitee.com/gitsc/pro-cloud/
 *     @Author Aijm 2929793435@qq.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cloud.common.data.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.cloud.common.util.util.StrUtils;
import com.cloud.common.util.var.StaticVar;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Aijm
 * @Description 获取request等
 * @Date 2020/4/23
 */
@UtilityClass
@Slf4j
public class ServletUtil {

    public static final String BEARER_TOKEN_TYPE = "Bearer ";

    public static final String BASIC_TOKEN_TYPE = "Basic ";

    /**
     * 得到request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    /**
     * 获取到servletPath
     * @return
     */
    public String getServletPath() {
        HttpServletRequest request = getRequest();
        return request.getServletPath();
    }

    /**
     * 得到response对象
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();

        return response;
    }

    /**
     * 获取用户token
     * @return
     */
    public static String getToken() {
        HttpServletRequest request = ServletUtil.getRequest();
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isNotBlank(header) && header.startsWith(BEARER_TOKEN_TYPE)) {
            return StrUtils.removePrefix(header, BEARER_TOKEN_TYPE);
        }
        return null;
    }

    /**
     * 从head中获取用户租户
     * @return
     */
    public static String getHeaderTenantId() {
        HttpServletRequest request = ServletUtil.getRequest();
        return request.getHeader(StaticVar.HEAD_USER_TENANT);
    }


    /**
     *  从head 中获取到  clientId 如果无 拿取默认securityProps 中内容
     * @param request
     * @param defaultClientId
     * @return
     */
    public static String getClientId(HttpServletRequest request, String defaultClientId) {
        // 从head中获取到 clientId
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        String clientId = defaultClientId;
        if (StrUtil.isNotBlank(header) && header.startsWith(ServletUtil.BASIC_TOKEN_TYPE)) {
            String[] tokens = ServletUtil.extractAndDecodeHeader(header);
            assert tokens.length == 2;
            clientId = tokens[0];
        }
        return clientId;
    }

    /**
     *  从head 中获取到  clientId 如果无 拿取默认securityProps 中内容
     * @param defaultClientId
     * @return
     */
    public static String getClientId(String defaultClientId) {
        return getClientId(getRequest(),defaultClientId);
    }

    /**
     * 获得用户远程地址
     * @param request
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request){
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }


    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(){
        HttpServletRequest request = getRequest();
        return getRemoteAddr(request);
    }


    /**
     * base64解析
     * @param header
     * @return
     */
    public static String[] extractAndDecodeHeader(String header) {

        String base64Token = header.substring(6);
        String token = Base64.decodeStr(base64Token);
        log.info("解密后的token为:{}", token);
        int delim = token.indexOf(':');
        return new String[] { token.substring(0, delim), token.substring(delim + 1) };
    }

}